#Title: Recursion
#Authors: Ricardo Padilla, Alexandra Neumann
#Description: The function named fix takes
	#2 integer values and uses recursion to
  #mimic the function in the handout.

############# Data Segment ###################
.data
prompt_i: .asciiz "Enter i (positive integer):"
prompt_x: .asciiz "Enter x (positive integer):"
answer: .asciiz "Answer:"

############# Code Segment ###################
.text
.globl main
main:
  	#Prompt user to enter i
  	la $a0, prompt_i
  	li $v0, 4
  	syscall

  	#Read value of i from user and store in register $s0
  	li $v0, 5
  	syscall
  	move $s0, $v0

  	#Prompt user to enter x
  	la $a0, prompt_x
  	li $v0,4
  	syscall

  	#Read value of x from user and store in register $s1
  	li $v0, 5
  	syscall
  	move $s1, $v0

  	#Passes i,x to function
  	move $a0, $s0
  	move $a1, $s1
  	jal fix
	move $s0, $v0

  	#Print out answer
  	la $a0, answer
  	li $v0, 4
  	syscall
  	move $a0, $s0
  	li $v0, 1
  	syscall

  	#Exit program
  	li $v0, 10
  	syscall

fix:
	#Save necessary registers to stack
	sw $ra, 0($sp)
	sw $s0, 4($sp)
	sw $s1, 8($sp)
	addi $sp, $sp, 12
  	move $s0, $a0
  	move $s1, $a1

	#Check if x>0, branch if not
  	blez $s1, chk_i
	move $a0, $s0
	subi $a1, $s1, 1
	jal fix
	j return

chk_i:
	#Check if i>0, branch if not
	blez $s0, zero
	subi $a0, $s0, 1
	subi $a1, $s0, 1
	jal fix
	addi $v0, $v0, 1
	j return

zero:
	#Return 0 if i<=0 and x<=0
	move $v0, $zero

return:
	#Restore necessary variables from
	#stack and return
	subi $sp, $sp, 4
	lw $s1, 0($sp)
	subi $sp, $sp, 4
	lw $s0, 0($sp)
	subi $sp, $sp, 4
	lw $ra, 0($sp)
   jr $ra 